/**************************************************************************** **
 * Copyright (C) 2001-2022 Inhand Networks, Inc.
 **************************************************************************** **/

/* ************************************************************************** **
 *     MODULE NAME            : system
 *     LANGUAGE               : C
 *     TARGET ENVIRONMENT     : Any
 *     FILE NAME              : daytime_inetd.c
 *     FIRST CREATION DATE    : 2022/11/18
 * --------------------------------------------------------------------------
 *     Version                : 1.0
 *     Author                 : EExuke
 *     Last Change            : 2022/11/18
 *     FILE DESCRIPTION       :
** ************************************************************************** */
#include <fcntl.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/syslog.h>
#include <time.h>
#include <unistd.h>

#define MAXLINE    4096    /* max text line length */

int main(int argc, char **argv)
{
	socklen_t len;
	struct sockaddr *cliaddr;
	time_t ticks;
	char buff[MAXLINE];

	//Welcome
	snprintf(buff, sizeof(buff), "**********************************************\n");
	write(0, buff, strlen(buff));
	snprintf(buff, sizeof(buff), "******** Welcome to my xinetd server! ********\n");
	write(0, buff, strlen(buff));
	snprintf(buff, sizeof(buff), "**********************************************\n");
	write(0, buff, strlen(buff));

	// timer run
	while (1) {
		//获取当前时间并转为字符串
		ticks = time(NULL);
		snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
		//因为网络中，将0重定向到了该socket文件描述符，所以向0写就相当于向socket写数据
		if (0 >= write(0, buff, strlen(buff))) {
			system("echo write_failed_exit > /home/xuke/daytime_inetd.log");
			break;
		}
		sleep(2);
	}

	//close TCP connection
	system("echo close_and_return >> /home/xuke/daytime_inetd.log");
	close(0);
	return 0;
}

